package com.rz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.Admin;
import com.rz.admin.entity.Consumer;
import com.rz.admin.entity.SysZone;
import com.rz.admin.entity.SysZoneExceptions;
import com.rz.admin.mapper.ConsumerMapper;
import com.rz.admin.mapper.ZoneExceptionsMapper;
import com.rz.admin.mapper.ZoneMapper;
import com.rz.admin.service.IConsumerService;
import com.rz.admin.service.IZoneService;
import com.rz.core.exception.GlobalException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 邮政分区
 * @Author maweiyue
 * @Date 2019/09/03 20:37
 */
@Component
public class SysZoneServiceImpl extends ServiceImpl<ZoneMapper, SysZone> implements IZoneService {

    @Resource
    ZoneExceptionsMapper zoneExceptionsMapper;

    /**
     * 根据国家代码和邮编获取分区，优先查询“分区例外情况表”，查询不到时再查“分区表”
     * @param country 国家代码
     * @param fromZip 出发地邮编
     * @param fromZip 目的地邮编
     * @return
     */
    public SysZone getByContryAndZip(String country, String fromZip, String toZip){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("county", country);
        queryWrapper.eq("zip", fromZip);
        queryWrapper.ge("end_zip", toZip);
        queryWrapper.le("start_zip", toZip);
        List<SysZoneExceptions> listExceptions = zoneExceptionsMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(listExceptions)) {
            // 如果例外情况查到了邮编对应的区号，则直接返回
            SysZoneExceptions exceptions = listExceptions.get(0);
            SysZone zone = new SysZone();
            BeanUtils.copyProperties(exceptions, zone);
            return zone;
        }

        // 例外中查不到时，再从分区表中查询
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("county", country);
        queryWrapper.eq("zip", fromZip);
        queryWrapper.ge("end_zip", toZip);
        queryWrapper.le("start_zip", toZip);
        List<SysZone> list = list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}
